/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;

import com.android.settings.R;
import com.hisense.settings.util.TvIntents;
import com.hisense.settings.util.Wrapper;
/*import com.marvell.willowtv.framework.features.ParentalControl;
import com.marvell.willowtv.framework.features.TvFramework;
import com.marvell.willowtv.framework.util.atsc.Events;
import com.marvell.willowtv.framework.util.atsc.PCEnumClass.RegionId;*/

/**
 * Handles settings menu for channel settings.
 * 
 * @author huangjiufa
 */
public class ProgramLockSettings extends PreferenceActivity implements
        Preference.OnPreferenceChangeListener {

    private static final String TAG = "ProgramLockSettings";

    private static final String KEY_RATING_ENABLE = "rating_enable";
    private static final String KEY_BLOCK_UNRATED = "block_untated";

    private static final String KEY_US_TV_RATING = "us_tv_rating";
    private static final String KEY_US_MOVIE_RATING = "us_movie_rating";
    private static final String KEY_CANADIAN_ENGLISH_RATING = "canadian_english_rating";
    private static final String KEY_CANADIAN_FREENCH_RATING = "canadian_french_rating";
    private static final String KEY_OPEN_VCHIP = "open_vchip";

    private ListPreference mUSTVRatingPreference;
    private ListPreference mUSMovieRatingPreference;
    private ListPreference mCanadianEnglishRatingPreference;
    private ListPreference mCanadianFrenchRatingPreference;
    // private ListPreference mOpnVChipPreference;
    private static CheckBoxPreference mRatingEnableCheckBox;
    private static CheckBoxPreference mBlockUnratedCheckBox;

    private PreferenceScreen openVChipList;

    //private ParentalControl mParentalControlSettings;

    private BroadcastReceiver mRRTReceiver;

    private static final int VALUE_DEFAULT_US_TV_RATING = 1;
    // 0 None
    // 1 G
    // 2 PG
    // 3 PG-13
    // 4 R
    // 5 NC-17
    // 6 X
    private static final int VALUE_DEFAULT_US_MOVIE_RATING = 0;
    // 0 E
    // 1 C
    // 2 C8+
    // 3 G
    // 4 PG
    // 5 14+
    // 6 18+
    private static final int VALUE_DEFAULT_CANADIAN_ENGLISH_RATING = 0;
    // 0 E
    // 1 G
    // 2 8ans+
    // 3 13ans+
    // 4 16ans+
    // 5 18ans+
    private static final int VALUE_DEFAULT_CANADIAN_FREENCH_RATING = 0;

    // private final ParentalControlSettings mPCSettings =
    // USDTVFramework.getInstance().getParentalControlSettingsInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setTitle(R.string.program_lock);
        addPreferencesFromResource(R.xml.program_lock_settings);

        mRatingEnableCheckBox = (CheckBoxPreference) findPreference(KEY_RATING_ENABLE);
        mBlockUnratedCheckBox = (CheckBoxPreference) findPreference(KEY_BLOCK_UNRATED);

        openVChipList = (PreferenceScreen) findPreference(KEY_OPEN_VCHIP);
        boolean flag_isChecked = mRatingEnableCheckBox.isChecked();
        Log.i(TAG, "-------in program lock settings , on create function----");
        /*boolean hasDRRT = TvFramework.getInstance().getParentalControlInstance()
                .getNumDimensionsAvailable(RegionId.REG_DRRT.ordinal()) != 0;
        Log.i(TAG, "------after get first hasDRRT----hasDRRT=  " + hasDRRT + "    ------"
                + "cccccccc=" + flag_isChecked);

        openVChipList.setEnabled(hasDRRT & flag_isChecked);*/
        receiveVchipStatus();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mRatingEnableCheckBox.setChecked(getRatingEnableStatus());
        mBlockUnratedCheckBox.setChecked(getBlockUnratedStatus());

        mUSMovieRatingPreference = (ListPreference) findPreference(KEY_US_MOVIE_RATING);
        int currentUSMovieRating = getUSMovieRating(VALUE_DEFAULT_US_MOVIE_RATING);

        Log.d(TAG, "9888888888888888888--------currentUSMovieRating=" + currentUSMovieRating);
        if ((7 == currentUSMovieRating) || (8 == currentUSMovieRating)) {
            Log.i(TAG, "777777777---currentUSMovieRating=" + currentUSMovieRating);
            if (7 == currentUSMovieRating) {
                currentUSMovieRating = 6;
            }
            if (8 == currentUSMovieRating) {
                currentUSMovieRating = 0;
            }
            mUSMovieRatingPreference.setValue((String.valueOf(currentUSMovieRating)));
            mUSMovieRatingPreference.setOnPreferenceChangeListener(this);
            updateUSMovieRatingSummary((String.valueOf(currentUSMovieRating)));

        }

        else {
            mUSMovieRatingPreference.setValue((String.valueOf(currentUSMovieRating - 1)));
            mUSMovieRatingPreference.setOnPreferenceChangeListener(this);
            updateUSMovieRatingSummary((String.valueOf(currentUSMovieRating - 1)));
        }

        mCanadianEnglishRatingPreference = (ListPreference) findPreference(KEY_CANADIAN_ENGLISH_RATING);
        int currentCanadianEnglishRating = getCanadianEnglishRating(VALUE_DEFAULT_CANADIAN_ENGLISH_RATING);
        Log.d(TAG, "9888888888888888888--------currentCanadianEnglishRating="
                + currentCanadianEnglishRating);
        if (currentCanadianEnglishRating == 7) {
            currentCanadianEnglishRating = 0;
        }
        mCanadianEnglishRatingPreference.setValue((String.valueOf(currentCanadianEnglishRating)));
        mCanadianEnglishRatingPreference.setOnPreferenceChangeListener(this);
        updateCanadianEnglishRatingSummary((String.valueOf(currentCanadianEnglishRating)));

        mCanadianFrenchRatingPreference = (ListPreference) findPreference(KEY_CANADIAN_FREENCH_RATING);
        int currentCanadianFrenchRating = getCanadianFrenchRating(VALUE_DEFAULT_CANADIAN_FREENCH_RATING);
        Log.d(TAG, "9888888888888888888--------currentCanadianFrenchRating="
                + currentCanadianFrenchRating);
        if (currentCanadianFrenchRating == 6) {
            currentCanadianFrenchRating = 0;
        }
        mCanadianFrenchRatingPreference.setValue((String.valueOf(currentCanadianFrenchRating)));
        mCanadianFrenchRatingPreference.setOnPreferenceChangeListener(this);
        updateCanadianFrenchRatingSummary((String.valueOf(currentCanadianFrenchRating)));

    }

    public boolean getRatingEnableStatus() {

        return ((Wrapper.getWrapperInstance().getPCRatingEnable() == 1) ? true : false);

    }

    public void setRatingEnableStatus(boolean enable) {
        Wrapper.getWrapperInstance().setPCRatingEnable((enable == true) ? 1 : 0);
    }

    public boolean getBlockUnratedStatus() {
        return ((Wrapper.getWrapperInstance().getBlockUnratedShows() == 1) ? true : false);

    }

    public void setBlockUnratedStatus(boolean enable) {

        Wrapper.getWrapperInstance().setBlockUnratedShows((enable == true) ? 1 : 0);
    }

    private void receiveVchipStatus() {
        mRRTReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null && TvIntents.ACTION_TV_EVENT.equals(intent.getAction())) {
                    /*int extra = intent.getIntExtra(TvIntents.EXTRA_USDTV_EVENT, -1);
                    if (extra == Events.RRT_DWNLD_UPDATE_EVENT.ordinal()) {
                        boolean flag_isChecked = mRatingEnableCheckBox.isChecked();
                        Log.i(TAG, "-------in program lock settings , onReceive function----");
                        boolean hasDRRT = TvFramework.getInstance().getParentalControlInstance()
                                .getNumDimensionsAvailable(RegionId.REG_DRRT.ordinal()) != 0;

                        openVChipList.setEnabled(hasDRRT & flag_isChecked);
                    }*/
                }
            }
        };

        final IntentFilter filter = new IntentFilter();
        filter.addAction(TvIntents.ACTION_TV_EVENT);
        registerReceiver(mRRTReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRRTReceiver != null) {
            unregisterReceiver(mRRTReceiver);
            mRRTReceiver = null;
        }
    }

    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {

        if (preference == mRatingEnableCheckBox) {
            boolean isChecked = ((CheckBoxPreference) preference).isChecked();
            setRatingEnableStatus(isChecked);

           /* boolean hasDRRT = TvFramework.getInstance().getParentalControlInstance()
                    .getNumDimensionsAvailable(RegionId.REG_DRRT.ordinal()) != 0;
            Log.i(TAG, "2222222222222222----hasDRRT=  " + hasDRRT + "    ------" + "cccccccc="
                    + isChecked);

            openVChipList.setEnabled(hasDRRT & isChecked);*/
        } else if (preference == mBlockUnratedCheckBox) {
            boolean isChecked = ((CheckBoxPreference) preference).isChecked();
            setBlockUnratedStatus(isChecked);
        } else {
            return super.onPreferenceTreeClick(preferenceScreen, preference);
        }

        return false;
    }

    public boolean onPreferenceChange(Preference preference, Object objValue) {
        final String key = preference.getKey();
        /*
         * if (KEY_US_TV_RATING.equals(key)) {
         * int value = Integer.parseInt((String) objValue);
         * try {
         * setUSTVRating(value);
         * updateUSTVRatingSummary(objValue);
         * } catch (NumberFormatException e) {
         * Log.e(TAG, "could not persist screen timeout setting", e);
         * }
         * }
         * else
         */if (KEY_US_MOVIE_RATING.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
                setUSMovieRating(value);
                updateUSMovieRatingSummary(objValue);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist screen timeout setting", e);
            }
        } else if (KEY_CANADIAN_ENGLISH_RATING.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
                setCanadianEnglishRating(value);
                updateCanadianEnglishRatingSummary(objValue);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist screen timeout setting", e);
            }
        } else if (KEY_CANADIAN_FREENCH_RATING.equals(key)) {
            int value = Integer.parseInt((String) objValue);
            try {
                setCanadianFrenchRating(value);
                updateCanadianFrenchRatingSummary(objValue);
            } catch (NumberFormatException e) {
                Log.e(TAG, "could not persist screen timeout setting", e);
            }
        }
        return true;
    }

    private boolean handleSelectItem(Object newValue) {

        return false;
    }

    private int getUSMovieRating(int defaultValue) {
        int value = defaultValue;

        value = Wrapper.getWrapperInstance().getUSAMovie();
        Log.d(TAG, "=========getUSMovieRating===== ---value: " + value);
        return value;
    }

    private void setUSMovieRating(int defaultValue) {
        int value = defaultValue;
        if (defaultValue == 0) {
            Wrapper.getWrapperInstance().setUSAMovie(8);
            return;
        }

        Wrapper.getWrapperInstance().setUSAMovie(defaultValue + 1);

        Log.d("setUSMovieRating", "============== ---defaultValue: " + defaultValue);

    }

    private void updateUSMovieRatingSummary(Object value) {
        CharSequence[] summaries = getResources().getTextArray(R.array.us_movie_rating_entries);
        CharSequence[] values = mUSMovieRatingPreference.getEntryValues();
        for (int i = 0; i < values.length; i++) {
            if (values[i].equals(value)) {
                mUSMovieRatingPreference.setSummary(summaries[i]);
                break;
            }
        }
    }

    private int getCanadianEnglishRating(int defaultValue) {
        int value = defaultValue;
        value = Wrapper.getWrapperInstance().getCANEnglish();
        Log.d("getCanadianEnglishRating", "============== ---value: " + value);
        return value;
    }

    private void setCanadianEnglishRating(int defaultValue) {
        int value = defaultValue;
        // TODO huangjiufa
        if (defaultValue == 0) {
            defaultValue = 7;
            Wrapper.getWrapperInstance().setCANEnglish(defaultValue);
            return;
        }
        Wrapper.getWrapperInstance().setCANEnglish(defaultValue);
        Log.d("setCanadianEnglishRating", "============== ---defaultvalue: " + defaultValue);
    }

    private void updateCanadianEnglishRatingSummary(Object value) {
        CharSequence[] summaries = getResources().getTextArray(
                R.array.canadian_english_rating_entries);
        CharSequence[] values = mCanadianEnglishRatingPreference.getEntryValues();
        for (int i = 0; i < values.length; i++) {
            if (values[i].equals(value)) {
                mCanadianEnglishRatingPreference.setSummary(summaries[i]);
                break;
            }
        }
    }

    private int getCanadianFrenchRating(int defaultValue) {
        int value = defaultValue;
        value = Wrapper.getWrapperInstance().getCANFrench();
        Log.d("getCanadianFrenchRating", "============== ---value: " + value);
        return value;
    }

    private void setCanadianFrenchRating(int defaultValue) {
        int value = defaultValue;
        if (defaultValue == 0) {
            defaultValue = 6;
            Wrapper.getWrapperInstance().setCANFrench(defaultValue);
            return;
        }
        Wrapper.getWrapperInstance().setCANFrench(defaultValue);
        Log.d("setCanadianFrenchRating", "============== ---defaultValue: " + defaultValue);

    }

    private void updateCanadianFrenchRatingSummary(Object value) {
        CharSequence[] summaries = getResources().getTextArray(
                R.array.canadian_french_rating_entries);
        CharSequence[] values = mCanadianFrenchRatingPreference.getEntryValues();
        for (int i = 0; i < values.length; i++) {
            if (values[i].equals(value)) {
                mCanadianFrenchRatingPreference.setSummary(summaries[i]);
                break;
            }
        }
    }

}
